package cz.byteworks.sandbox.html5.newsbox.jms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.springframework.beans.factory.annotation.Autowired;

import cz.byteworks.sandbox.html5.newsbox.app.FixedSizeQueue;
import cz.byteworks.sandbox.html5.newsbox.model.NewsMessage;

public class JmsMessageReceiver implements MessageListener {

    @Autowired(required = true)
    private FixedSizeQueue<NewsMessage> webContainerMessageQueue;
    
    @Override
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            try {
                if (((ObjectMessage) message).getObject() != null && ((ObjectMessage) message).getObject() instanceof NewsMessage) {
                    NewsMessage newsMessage = (NewsMessage) ((ObjectMessage) message).getObject();
                    webContainerMessageQueue.add(newsMessage);
                }
                else {
                    throw new ClassCastException("Unable to convert " + ((ObjectMessage) message).getObject() == null ? 
                            "null" : ((ObjectMessage) message).getObject().getClass().getName() + " into NewsMessage object");
                }
            } catch (JMSException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
        else {
            throw new IllegalArgumentException("Unsupported message type " + message.getClass().getName() + ". Only ObjectMessage is supported.");
        }
    }

}
